package com.jiazhong.shopping.servlets;

import com.jiazhong.shopping.dao.EatDao;
import com.jiazhong.shopping.dao.CarDao;
import com.jiazhong.shopping.dao.impl.EatDaoImpl;
import com.jiazhong.shopping.dao.impl.CarDaoImpl;
import com.jiazhong.shopping.model.Eat;
import com.jiazhong.shopping.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Servlet的功能是:
 *  1.获得客户端请求
 *  2.调用处理类中的处理方法，进行功能处理
 *  3.根据处理结果进行页面跳转
 */
@WebServlet("/eat.do")
public class EatServlet extends BaseServlet {
    /**
     * 查询所有商品的Servlet
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void queryEats(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //调用处理类中的处理方法，进行功能处理
        //创建EatDao对象
        EatDao eatDao = new EatDaoImpl();
        //调用处理方法,查询所有食品方法
        List<Eat> eatList = eatDao.queryEats();

        //获得当前登录用户的购物车中商品的数量
        User user = (User)request.getSession().getAttribute("user");
        if(user!=null){//用户已登录
            CarDao carDao = new CarDaoImpl();
            //获得购物车中商品的数量
            int count = carDao.queryCountByUserId(user.getUser_id());
            //将count存入到request对象中
            request.setAttribute("count",count);
        }

        //将eatList存入到request作用域中
        //向request对象中添加了一个属性，属性名:eatList,属性值:eatList对象
        request.setAttribute("eatList",eatList);
        //请求转发到showEatList.jsp页面
        request.getRequestDispatcher("showEatList.jsp").forward(request,response);

    }

    /**
     * 根据菜品编号获得菜对象
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void queryEatById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得客户端提交的参数,从页面上传入的参数都是字符串
        int eatId = Integer.parseInt(request.getParameter("eat_id"));
        //2.调用处理类中的处理方法，进行功能处理
        EatDao userDao = new EatDaoImpl();
        Eat eat = userDao.queryEatById(eatId);
        //3.根据处理结果进行页面跳转
        //将eat对象添加request对象中
        request.setAttribute("eat",eat);
        //请求转发到showBookDesc.jsp页面
        request.getRequestDispatcher("showEatDesc.jsp").forward(request,response);
    }
}
